import os
import sys
import subprocess
import platform

def check_python():
    """检查Python版本"""
    print("检查Python版本...")
    version = sys.version_info
    if version.major < 3 or (version.major == 3 and version.minor < 8):
        print("错误: 需要Python 3.8或更高版本")
        return False
    print(f"Python版本: {sys.version}")
    return True

def install_requirements():
    """安装依赖包"""
    print("安装依赖包...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("依赖包安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"安装依赖包失败: {e}")
        return False

def setup_environment():
    """设置环境变量"""
    print("检查环境变量...")
    env_file = ".env"
    
    if not os.path.exists(env_file):
        print("创建.env文件...")
        with open(env_file, "w", encoding="utf-8") as f:
            f.write("# 基本配置\n")
            f.write("STORAGE_PATH=./reports\n")
            f.write("SCHEDULE_TIME=11:50\n")
            f.write("RUN_IMMEDIATELY=false\n\n")
            
            f.write("# 邮件配置\n")
            f.write("ENABLE_EMAIL=true\n")
            f.write("SMTP_SERVER=smtp.example.com\n")
            f.write("SMTP_PORT=465\n")
            f.write("SMTP_USER=your_email@example.com\n")
            f.write("SMTP_PASSWORD=your_password\n")
            f.write("RECIPIENTS=recipient1@example.com,recipient2@example.com\n\n")
            
            f.write("# API密钥\n")
            f.write("DEEPSEEK_API_KEY=your_api_key\n")
        
        print("已创建.env文件，请编辑该文件填入正确的配置信息")
        return False
    else:
        print(".env文件已存在")
        return True

def create_service_file():
    """创建系统服务文件"""
    print("创建系统服务文件...")
    
    # 获取当前工作目录的绝对路径
    current_dir = os.path.abspath(os.getcwd())
    python_path = sys.executable
    
    if platform.system() == "Linux":
        service_content = f"""[Unit]
Description=NewsBot Service
After=network.target

[Service]
Type=simple
User={os.getenv('USER', 'root')}
WorkingDirectory={current_dir}
ExecStart={python_path} {os.path.join(current_dir, 'main.py')}
Restart=always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=newsbot

[Install]
WantedBy=multi-user.target
"""
        service_file = "newsbot.service"
        with open(service_file, "w") as f:
            f.write(service_content)
        
        print(f"已创建服务文件: {service_file}")
        print("请执行以下命令安装服务:")
        print(f"sudo cp {service_file} /etc/systemd/system/")
        print("sudo systemctl daemon-reload")
        print("sudo systemctl enable newsbot.service")
        print("sudo systemctl start newsbot.service")
    
    elif platform.system() == "Windows":
        bat_content = f"""@echo off
cd /d {current_dir}
"{python_path}" "{os.path.join(current_dir, 'main.py')}"
"""
        bat_file = "start_newsbot.bat"
        with open(bat_file, "w") as f:
            f.write(bat_content)
        
        print(f"已创建启动脚本: {bat_file}")
        print("请将此脚本添加到Windows计划任务中，设置为开机自动运行")
        
        # 创建计划任务的命令
        task_cmd = f'schtasks /create /tn "NewsBot" /tr "{os.path.join(current_dir, bat_file)}" /sc onstart /ru SYSTEM'
        print("或者执行以下命令创建开机自启动任务:")
        print(task_cmd)
    
    else:
        print(f"不支持的操作系统: {platform.system()}")
        return False
    
    return True

def main():
    """主函数"""
    print("开始部署NewsBot...")
    
    if not check_python():
        return
    
    if not setup_environment():
        print("请先编辑.env文件，然后重新运行此脚本")
        return
    
    if not install_requirements():
        return
    
    create_service_file()
    
    print("\n部署完成！")
    print("请确保.env文件中的配置正确，然后按照上述说明启动服务")

if __name__ == "__main__":
    main()